package com.sumainfor.pc.gmio.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.WxUserEntity;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.DateUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.util.SystemUtils;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.gmio.dao.QuestionnaireMapper;
import com.sumainfor.pc.gmio.feign.BaseTenantFeign;
import com.sumainfor.pc.gmio.service.QuestionnaireService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Jack Chen
 * @Create 2019-01-23 17:16
 * 问卷调查
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Log4j2
public class QuestionnaireServiceImpl implements QuestionnaireService {

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private BaseTenantFeign tenantFeign;

    @Autowired
    private ComUtils comUtils;

    /**
     * 查询表格数据列表
     *
     * @param page
     * @param params 条件
     * @return
     */
    @Override
    public JsonResult selectTableList(Page page, Map<String, Object> params) {
        IPage<Map<String, Object>> iPage = questionnaireMapper.selectQuestionnaireList(page, params);
        iPage.setRecords(iPage.getRecords().stream().map(item -> {
            String tenId = MapUtils.getString(item, "TenId");
            //查询租客信息
            JsonResult result = tenantFeign.getWxInfoByTenId(tenId);
            if (!result.isSuccess()) {
                log.info("Error ==> {}", result.getErrorMessage());
                throw new TCException("没有查询到租客的信息");
            }
            WxUserEntity entity = JSONObject.parseObject(((JSONObject) result.getResult()).toJSONString(), WxUserEntity.class);

            //租客姓名
            item.put("userName", entity.getRealName());
            item.put("phone", entity.getTenPhone());
            DateUtils.formatDateByMap(item);
            return item;
        }).collect(Collectors.toList()));
        return JsonResult.success(iPage);
    }


    /**
     * 获得用户回答的问题信息数据
     *
     * @param tenSurId
     * @return
     */
    @Override
    public JsonResult getQuestionnaireInfo(String tenSurId) {
        List<Map<String, Object>> topic = questionnaireMapper.selectQuestionnaireInfo(tenSurId);
        for (Map<String, Object> map : topic) {
            String picture = MapUtils.getString(map, "Picture");
            if (StringUtils.isNotBlank(picture)) {
                map.put("Picture", JSONObject.parseArray(picture, String.class));
            }
        }
        return JsonResult.success(topic);
    }


    /**
     * 提交线上与线下建议
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult submitSurvey(Map<String, Object> params) {
        //获取租客编号
        String tenId = MapUtils.getString(params, "TenId");
        String answer = MapUtils.getString(params, "Answer");
        Integer type = MapUtils.getInteger(params, "TenType");
        List<String> picture = (List<String>) MapUtils.getObject(params, "Picture");

        //问卷调查主编号
        String tenSurId = comUtils.getLocalTrmSeqNumByLook("TS", Constants.DATA_SOURCE_GMIO, "tcgmio_survey_tenant", "TenSurId");
        int row = questionnaireMapper.insertSurveyMain(ParamsCommon.commonInsertParms(CustomMap.create()
                .put("TenSurId", tenSurId)
                .put("TenType", type)
                .put("TenId", tenId)
                .put("CreateTime", new Date())));
        if (row <= 0) {
            return JsonResult.error("插入数据失败:" + SystemUtils.getLineNumber());
        }

        //插入中间表数据
        row = questionnaireMapper.insertSurveyCenter(ParamsCommon.commonInsertParms(CustomMap.create()
                .put("TenSurId", tenSurId)
                .put("Answer", answer)
                .put("Picture", JSONObject.toJSONString(picture))));

        if (row <= 0) {
            throw new TCException("插入数据失败:" + SystemUtils.getLineNumber());
        }
        return JsonResult.actionSuccess();
    }

}
